package com.chb.mains;

/**
 * @author CHB
 * @createTime 2022-7-9 10:03
 */
public class GetArrMaxLen {

    public static void main(String[] args) {
        GetArrMaxLen getArrMaxLen = new GetArrMaxLen();
        System.out.println(getArrMaxLen.getMaxLen(new int[]{ 1,-2,3,0,1 }));
    }
    public int getMaxLen(int[] nums) {
        int length = nums.length;
        int[] positive = new int[length];
        int[] negative = new int[length];
        if (nums[0] > 0) {
            positive[0] = 1;
        } else if (nums[0] < 0) {
            negative[0] = 1;
        }
        int maxLength = positive[0];
        for (int i = 1; i < length; i++) {
            if (nums[i] > 0) {
                positive[i] = positive[i - 1] + 1;
                negative[i] = negative[i - 1] > 0 ? negative[i - 1] + 1 : 0;
            } else if (nums[i] < 0) {
                positive[i] = negative[i - 1] > 0 ? negative[i - 1] + 1 : 0;
                negative[i] = positive[i - 1] + 1;
            } else {
                positive[i] = 0;
                negative[i] = 0;
            }
            maxLength = Math.max(maxLength, positive[i]);
        }
        return maxLength;
    }


    public int getMaxLen1(int[] nums) {
        if(nums.length <= 0){
            return 0;
        }
        // 1代表乘积为正数，-1代表乘积为负数
        int cur = 1;
        int maxLen = 0;
        int preNegative = -1;
        int preZero = -1;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] == 0){
                // 判断字符长度
                maxLen = this.getMax(i,preNegative,cur,i,maxLen);
                preZero = i;
                cur = 1;
                continue;
            }
            if(nums[i] < 0){
                cur *= -1;
                preNegative = i;
            }
        }
        maxLen = this.getMax(preZero,preNegative,cur,nums.length-1,maxLen);
        return maxLen;
    }
// -1,-2,-3,0,1
    private int getMax(int zeroIdx,int negativeIdx,int cur,int curIdx,int maxLen){
        int curLen = curIdx - zeroIdx;
        if(zeroIdx < cur){
            curLen --;
        }
        // 算的乘积为正数
        if(cur == 1){
            if(curLen > maxLen){
                return curLen;
            }
        }else {
            // 从上一个负数下标分成左右两部分
            int lLen = 0;
            int rLen = 0;
            // 说明是遇见0的情况，此时下标位置关系为 数组开始位置，negativeIdx，0
            // if(cur == zeroIdx){
                lLen = negativeIdx - zeroIdx - 1;
                rLen = curIdx - negativeIdx;
            // }else {
            //     // 下标位置关系为 0，negativeIdx，当前位置
            // }
            if(lLen >= rLen){
                if(lLen > maxLen){
                    return lLen;
                }
            }else {
                if(rLen > maxLen){
                    return rLen;
                }
            }
        }
        return maxLen;
    }
}
